<!DOCTYPE html>





<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="generator" content="Hexo 3.9.0">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.3.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.3.0">
  <link rel="mask-icon" href="/images/logo.svg?v=7.3.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.3.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.3.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    save_scroll: false,
    copycode: {"enable":false,"show_result":false,"style":null},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    }
  };
</script>

  <meta name="description" content="前言Context被翻译为上下文，在编程领域，这是一个经常会接触到的概念，React中也有。 在React的官方文档中，Context被归类为高级部分(Advanced)，属于React的高级API，但官方并不建议在稳定版的App中使用Contex。 不过，这并非意味着我们不需要关注Context。事实上，很多优秀的React组件都通过Context来完成自己的功能，比如react-redux的">
<meta name="keywords" content="学习笔记和总结,react">
<meta property="og:type" content="article">
<meta property="og:title" content="React context基本用法总结">
<meta property="og:url" content="http://yoursite.com/2019/11/14/2019/11/React context基本用法总结/index.html">
<meta property="og:site_name" content="淡退">
<meta property="og:description" content="前言Context被翻译为上下文，在编程领域，这是一个经常会接触到的概念，React中也有。 在React的官方文档中，Context被归类为高级部分(Advanced)，属于React的高级API，但官方并不建议在稳定版的App中使用Contex。 不过，这并非意味着我们不需要关注Context。事实上，很多优秀的React组件都通过Context来完成自己的功能，比如react-redux的">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://desk-fd.zol-img.com.cn/t_s1024x768c5/g5/M00/0C/02/ChMkJ13V9q6IOSp_AAPNPlvQOwwAAvV_QJYgfoAA81W947.jpg">
<meta property="og:updated_time" content="2019-12-08T13:06:33.252Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="React context基本用法总结">
<meta name="twitter:description" content="前言Context被翻译为上下文，在编程领域，这是一个经常会接触到的概念，React中也有。 在React的官方文档中，Context被归类为高级部分(Advanced)，属于React的高级API，但官方并不建议在稳定版的App中使用Contex。 不过，这并非意味着我们不需要关注Context。事实上，很多优秀的React组件都通过Context来完成自己的功能，比如react-redux的">
<meta name="twitter:image" content="https://desk-fd.zol-img.com.cn/t_s1024x768c5/g5/M00/0C/02/ChMkJ13V9q6IOSp_AAPNPlvQOwwAAvV_QJYgfoAA81W947.jpg">
  <link rel="canonical" href="http://yoursite.com/2019/11/14/2019/11/React context基本用法总结/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>React context基本用法总结 | 淡退</title>
  








  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  <div class="container sidebar-position-left">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">淡退</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">---脂肪肝患者</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-about">
      
    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-tags">
      
    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-categories">
      
    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a href="javascript:;" class="popup-trigger">
        
          <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
      </li>
    
  </ul>

</nav>
  <div class="site-search">
    
  <div class="popup search-popup">
  <div class="search-header">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <div class="search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="search-input">
    </div>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>
  <div id="search-result"></div>
</div>


  </div>
</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content page-post-detail">
            

  <div id="posts" class="posts-expand">
    

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/11/14/2019/11/React context基本用法总结/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="淡退">
      <meta itemprop="description" content="欢迎你的到来！">
      <meta itemprop="image" content="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565847089857&di=2bb546a711f57b819a4dbf3584c66392&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F458af12108c4da0f1cf4fe8e2713a458898e332b28196-jdjJ3j_fw658">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="淡退">
    </span>
      <header class="post-header">
        
          <i class="fa fa-thumb-tack"></i>
          <font color=7D26CD>置顶</font>
        

        
          <h1 class="post-title" itemprop="name headline">React context基本用法总结

            
          </h1>
        

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-11-14 23:10:17" itemprop="dateCreated datePublished" datetime="2019-11-14T23:10:17+08:00">2019-11-14</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-12-08 21:06:33" itemprop="dateModified" datetime="2019-12-08T21:06:33+08:00">2019-12-08</time>
              </span>
            
          
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a></span>

                
                
              
            </span>
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <div class="post-gallery" itemscope itemtype="http://schema.org/ImageGallery">
            <div class="post-gallery-row">
              <img src="https://desk-fd.zol-img.com.cn/t_s1024x768c5/g5/M00/0C/02/ChMkJ13V9q6IOSp_AAPNPlvQOwwAAvV_QJYgfoAA81W947.jpg" itemprop="contentUrl">
            
          

          </div>
        </div>
        <a id="more"></a>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p><code>Context</code>被翻译为上下文，在编程领域，这是一个经常会接触到的概念，React中也有。</p>
<p>在<code>React</code>的官方文档中，<code>Context</code>被归类为高级部分<code>(Advanced)</code>，属于React的高级API，但官方并不建议在稳定版的App中使用<code>Contex</code>。</p>
<p>不过，这并非意味着我们不需要关注<code>Context</code>。事实上，很多优秀的<code>React</code>组件都通过<code>Context</code>来完成自己的功能，比如<code>react-redux的&lt;Provider /&gt;</code>，就是通过<code>Context</code>提供一个全局态的<code>store</code>，拖拽组件r<code>eact-dnd</code>，通过<code>Context</code>在组件中分发<code>DOM</code>的<code>Drag</code>和<code>Drop</code>事件，路由组件<code>react-router</code>通过<code>Context</code>管理路由状态等等。在React组件开发中，如果用好Context，可以让你的组件变得强大，而且灵活。</p>
<h3 id="初识React-Context"><a href="#初识React-Context" class="headerlink" title="初识React Context"></a>初识React Context</h3><p>当你不想在组件树中通过逐层传递<code>props</code>或者<code>state</code>的方式来传递数据时，可以使用Context来实现跨层级的组件数据传递。<br><img src="https://upload-images.jianshu.io/upload_images/1457831-b19e007758f57df7?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt><br>使用<code>props</code>或者<code>state</code>传递数据，数据自顶下流。<br><img src="https://upload-images.jianshu.io/upload_images/1457831-1b8e3c5ce88f7758?imageMogr2/auto-orient/strip%7CimageView2/2/w/1200/format/webp" alt><br>使用Context，可以跨越组件进行数据传递。</p>
<h3 id="如何使用Context"><a href="#如何使用Context" class="headerlink" title="如何使用Context"></a>如何使用Context</h3><p>如果要Context发挥作用，需要用到两种组件，一个是<code>Context生产者(Provider)</code>，通常是一个父节点，另外是一个<code>Context的消费者(Consumer)</code>，通常是一个或者多个子节点。所以Context的使用基于生产者消费者模式。</p>
<p>对于父组件，也就是Context生产者，需要通过一个静态属性<code>childContextTypes</code>声明提供给子组件的Context对象的属性，并实现一个实例g<code>etChildContext</code>方法，返回一个代表Context的纯对象 (plain object) 。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">import React from &apos;react&apos;</span><br><span class="line">import PropTypes from &apos;prop-types&apos;</span><br><span class="line"></span><br><span class="line">class MiddleComponent extends React.Component &#123;</span><br><span class="line">  render () &#123;</span><br><span class="line">    return &lt;ChildComponent /&gt;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">class ParentComponent extends React.Component &#123;</span><br><span class="line">  // 声明Context对象属性</span><br><span class="line">  static childContextTypes = &#123;</span><br><span class="line">    propA: PropTypes.string,</span><br><span class="line">    methodA: PropTypes.func</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  // 返回Context对象，方法名是约定好的</span><br><span class="line">  getChildContext () &#123;</span><br><span class="line">    return &#123;</span><br><span class="line">      propA: &apos;propA&apos;,</span><br><span class="line">      methodA: () =&gt; &apos;methodA&apos;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  render () &#123;</span><br><span class="line">    return &lt;MiddleComponent /&gt;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而对于Context的消费者，通过如下方式访问父组件提供的Context。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">import React from &apos;react&apos;</span><br><span class="line">import PropTypes from &apos;prop-types&apos;</span><br><span class="line"></span><br><span class="line">class ChildComponent extends React.Component &#123;</span><br><span class="line">  // 声明需要使用的Context属性</span><br><span class="line">  static contextTypes = &#123;</span><br><span class="line">    propA: PropTypes.string</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  render () &#123;</span><br><span class="line">    const &#123;</span><br><span class="line">      propA,</span><br><span class="line">      methodA</span><br><span class="line">    &#125; = this.context</span><br><span class="line">    </span><br><span class="line">    console.log(`context.propA = $&#123;propA&#125;`)  // context.propA = propA</span><br><span class="line">    console.log(`context.methodA = $&#123;methodA&#125;`)  // context.methodA = undefined</span><br><span class="line">    </span><br><span class="line">    return ...</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>子组件需要通过一个静态属性<code>contextTypes</code>声明后，才能访问父组件<code>Context</code>对象的属性，否则，即使属性名没写错，拿到的对象也是<code>undefined</code>。</p>
<p>对于无状态子组件(Stateless Component)，可以通过如下方式访问父组件的Context</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">import React from &apos;react&apos;</span><br><span class="line">import PropTypes from &apos;prop-types&apos;</span><br><span class="line"></span><br><span class="line">const ChildComponent = (props, context) =&gt; &#123;</span><br><span class="line">  const &#123;</span><br><span class="line">    propA</span><br><span class="line">  &#125; = context</span><br><span class="line">    </span><br><span class="line">  console.log(`context.propA = $&#123;propA&#125;`)  // context.propA = propA</span><br><span class="line">    </span><br><span class="line">  return ...</span><br><span class="line">&#125;</span><br><span class="line">  </span><br><span class="line">ChildComponent.contextProps = &#123;</span><br><span class="line">  propA: PropTypes.string    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而在接下来的发行版本中，React对Context的API做了调整，更加明确了生产者消费者模式的使用方式。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">import React from &apos;react&apos;;</span><br><span class="line">import ReactDOM from &apos;react-dom&apos;;</span><br><span class="line"></span><br><span class="line">const ThemeContext = React.createContext(&#123;</span><br><span class="line">  background: &apos;red&apos;,</span><br><span class="line">  color: &apos;white&apos;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>通过静态方法<code>React.createContext()</code>创建一个Context对象，这个Context对象包含两个组件，<code>&lt;Provider /&gt;和&lt;Consumer /&gt;</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">class App extends React.Component &#123;</span><br><span class="line">  render () &#123;</span><br><span class="line">    return (</span><br><span class="line">      &lt;ThemeContext.Provider value=&#123;&#123;background: &apos;green&apos;, color: &apos;white&apos;&#125;&#125;&gt;</span><br><span class="line">        &lt;Header /&gt;</span><br><span class="line">      &lt;/ThemeContext.Provider&gt;</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>&lt;Provider /&gt;</code>的value相当于现在的<code>getChildContext()</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">class Header extends React.Component &#123;</span><br><span class="line">  render () &#123;</span><br><span class="line">    return (</span><br><span class="line">      &lt;Title&gt;Hello React Context API&lt;/Title&gt;</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"> </span><br><span class="line">class Title extends React.Component &#123;</span><br><span class="line">  render () &#123;</span><br><span class="line">    return (</span><br><span class="line">      &lt;ThemeContext.Consumer&gt;</span><br><span class="line">        &#123;context =&gt; (</span><br><span class="line">          &lt;h1 style=&#123;&#123;background: context.background, color: context.color&#125;&#125;&gt;</span><br><span class="line">            &#123;this.props.children&#125;</span><br><span class="line">          &lt;/h1&gt;</span><br><span class="line">        )&#125;</span><br><span class="line">      &lt;/ThemeContext.Consumer&gt;</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>&lt;Consumer /&gt;</code>的children必须是一个函数，通过函数的参数获取<code>&lt;Provider /&gt;提供的Context</code>。<br>可见，Context的新API更加贴近React的风格。</p>
<h3 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h3><p>React的context就是一个全局变量，可以从根组件跨级别在React的组件中传递。React context 的API 有两个版本,React16.x 之前 的是老版本的 context，之后的是新版本的context。</p>
<h4 id="1-老版本的context"><a href="#1-老版本的context" class="headerlink" title="1.老版本的context"></a>1.老版本的context</h4><p><code>getChildContext</code>根组件中声明，一个函数，返回一个对象,就是context <code>childContextTyp</code>e根组件中声明,指定context的结构类 型，如不指定,会产生错误<br><code>contextTypes</code>子孙组件中声明，指定要接收的context的结构类型，可以只是context的一部分结构。contextTypes 没有定义，context将是一个空对象。<br><code>this.context</code> 在子孙组件中通过此来获取上下文</p>
<blockquote>
<p>(注:从React v15.5开始 ，React.PropTypes 助手函数已被弃用，可使用 prop-types 库 来定义contextTypes)</p>
</blockquote>
<p>举例如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br></pre></td><td class="code"><pre><span class="line">//根组件</span><br><span class="line">class MessageList extends React.Component &#123;</span><br><span class="line">  getChildContext() &#123;</span><br><span class="line">    return &#123;color: &quot;purple&quot;,text: &quot;item text&quot;&#125;;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line">    const children = this.props.messages.map((message) =&gt;</span><br><span class="line">      &lt;Message text=&#123;message.text&#125; /&gt;</span><br><span class="line">    );</span><br><span class="line">    return &lt;div&gt;&#123;children&#125;&lt;/div&gt;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">MessageList.childContextTypes = &#123;</span><br><span class="line">  color: React.PropTypes.string</span><br><span class="line">  text: React.PropTypes.string</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">//中间组件</span><br><span class="line">class Message extends React.Component &#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    return (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">        &lt;MessageItem /&gt;</span><br><span class="line">        &lt;Button&gt;Delete&lt;/Button&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//孙组件(接收组件)</span><br><span class="line">class MessageItem extends React.Component &#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    return (</span><br><span class="line">      &lt;div&gt;</span><br><span class="line">        &#123;this.context.text&#125;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">MessageItem.contextTypes = &#123;</span><br><span class="line">  text: React.PropTypes.string</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line">class Button extends React.Component &#123;</span><br><span class="line">  render() &#123;</span><br><span class="line">    return (</span><br><span class="line">      &lt;button style=&#123;&#123;background: this.context.color&#125;&#125;&gt;</span><br><span class="line">        &#123;this.props.children&#125;</span><br><span class="line">      &lt;/button&gt;</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Button.contextTypes = &#123;</span><br><span class="line">  color: React.PropTypes.string</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h4 id="2-新版本的context"><a href="#2-新版本的context" class="headerlink" title="2.新版本的context"></a>2.新版本的context</h4><p>新版本的React context使用了Provider和Customer模式，和react-redux的模式非常像。在顶层的Provider中传入value，<br>在子孙级的Consumer中获取该值，并且能够传递函数，用来修改context，如下代码所示：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">//创建Context组件</span><br><span class="line">const ThemeContext = React.createContext(&#123;</span><br><span class="line">  theme: &apos;dark&apos;,</span><br><span class="line">  toggle: () =&gt; &#123;&#125;, //向上下文设定一个回调方法</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line">//运行APP</span><br><span class="line">class App extends React.Component &#123;</span><br><span class="line">  constructor(props) &#123;</span><br><span class="line">    super(props);</span><br><span class="line"></span><br><span class="line">    this.toggle = () =&gt; &#123; //设定toggle方法，会作为context参数传递</span><br><span class="line">      this.setState(state =&gt; (&#123;</span><br><span class="line">        theme:</span><br><span class="line">          state.theme === themes.dark</span><br><span class="line">            ? themes.light</span><br><span class="line">            : themes.dark,</span><br><span class="line">      &#125;));</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    this.state = &#123;</span><br><span class="line">      theme: themes.light,</span><br><span class="line">      toggle: this.toggle,</span><br><span class="line">    &#125;;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  render() &#123;</span><br><span class="line">    return (</span><br><span class="line">      &lt;ThemeContext.Provider value=&#123;this.state&#125;&gt; //state包含了toggle方法</span><br><span class="line">        &lt;Content /&gt;</span><br><span class="line">      &lt;/ThemeContext.Provider&gt;</span><br><span class="line">    );</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//中间组件</span><br><span class="line">function Content() &#123;</span><br><span class="line">  return (</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">      &lt;Button /&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//接收组件</span><br><span class="line">function Button() &#123;</span><br><span class="line">  return (</span><br><span class="line">    &lt;ThemeContext.Consumer&gt;</span><br><span class="line">      &#123;(&#123;theme, toggle&#125;) =&gt; (</span><br><span class="line">        &lt;button</span><br><span class="line">          onClick=&#123;toggle&#125; //调用回调</span><br><span class="line">          style=&#123;&#123;backgroundColor: theme&#125;&#125;&gt;</span><br><span class="line">          Toggle Theme</span><br><span class="line">        &lt;/button&gt;</span><br><span class="line">      )&#125;</span><br><span class="line">    &lt;/ThemeContext.Consumer&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>详细用法可以参考官方文档：<a href="https://react.docschina.org/docs/context.html#reactcreatecontext" target="_blank" rel="noopener">https://react.docschina.org/docs/context.html#reactcreatecontext</a></p>
<h4 id="3-context在如下的生命周期钩子中可以使用"><a href="#3-context在如下的生命周期钩子中可以使用" class="headerlink" title="3. context在如下的生命周期钩子中可以使用"></a>3. context在如下的生命周期钩子中可以使用</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">constructor(props, context)</span><br><span class="line">componentWillReceiveProps(nextProps, nextContext)</span><br><span class="line">shouldComponentUpdate(nextProps, nextState, nextContext)</span><br><span class="line">componentWillUpdate(nextProps, nextState, nextContext)</span><br><span class="line">componentDidUpdate(prevProps, prevState, prevContext)</span><br></pre></td></tr></table></figure>

<h4 id="4-在无状态组件中可以通过参数传入"><a href="#4-在无状态组件中可以通过参数传入" class="headerlink" title="4. 在无状态组件中可以通过参数传入"></a>4. 在无状态组件中可以通过参数传入</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">function D(props, context) &#123;</span><br><span class="line">  return (</span><br><span class="line">    &lt;div&gt;&#123;this.context.user.name&#125;&lt;/div&gt;</span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">D.contextTypes = &#123;</span><br><span class="line">  user: React.PropTypes.object.isRequired</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="5-React-context的局限性"><a href="#5-React-context的局限性" class="headerlink" title="5. React context的局限性"></a>5. React context的局限性</h4><ol>
<li>在组件树中，如果中间某一个组件 <code>ShouldComponentUpdate returning false</code> 了，会阻碍 context 的正常传值，导致子组件无法获取更新。</li>
<li>组件本身 <code>extends React.PureComponent</code> 也会阻碍 context 的更新。</li>
</ol>
<blockquote>
<p>注意点：</p>
<ol>
<li>Context 应该是唯一不可变的. </li>
<li>组件只在初始化的时候去获取 Context</li>
</ol>
</blockquote>
<p>参考: </p>
<ol>
<li><a href="https://www.tuicool.com/articles/nUryimf" target="_blank" rel="noopener">https://www.tuicool.com/articles/nUryimf</a></li>
<li><a href="https://segmentfault.com/a/1190000012575622" target="_blank" rel="noopener">https://segmentfault.com/a/1190000012575622</a></li>
<li><a href="https://www.jianshu.com/p/eba2b76b290b" target="_blank" rel="noopener">https://www.jianshu.com/p/eba2b76b290b</a></li>
</ol>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/学习笔记和总结/" rel="tag"># 学习笔记和总结</a>
            
              <a href="/tags/react/" rel="tag"># react</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/11/13/2019/11/ES6 Promise原生实现 、 Generator深入学习/" rel="next" title="ES6 Promise原生实现 、 Generator深入学习">
                  <i class="fa fa-chevron-left"></i> ES6 Promise原生实现 、 Generator深入学习
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2019/11/14/2019/11/Hexo搭建个人博客/" rel="prev" title="Hexo搭建个人博客">
                  Hexo搭建个人博客 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">

          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image"
      src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565847089857&di=2bb546a711f57b819a4dbf3584c66392&imgtype=0&src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F458af12108c4da0f1cf4fe8e2713a458898e332b28196-jdjJ3j_fw658"
      alt="淡退">
  <p class="site-author-name" itemprop="name">淡退</p>
  <div class="site-description motion-element" itemprop="description">欢迎你的到来！</div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">14</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-categories">
        
          
            <a href="/categories/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
          
            <a href="/tags/">
          
        
        
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
          
        
        <span class="site-state-item-count">10</span>
        <span class="site-state-item-name">标签</span>
        </a>
      </div>
    
  </nav>



        </div>
      </div>
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#初识React-Context"><span class="nav-number">1.1.</span> <span class="nav-text">初识React Context</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何使用Context"><span class="nav-number">1.2.</span> <span class="nav-text">如何使用Context</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结："><span class="nav-number">1.3.</span> <span class="nav-text">总结：</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-老版本的context"><span class="nav-number">1.3.1.</span> <span class="nav-text">1.老版本的context</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-新版本的context"><span class="nav-number">1.3.2.</span> <span class="nav-text">2.新版本的context</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-context在如下的生命周期钩子中可以使用"><span class="nav-number">1.3.3.</span> <span class="nav-text">3. context在如下的生命周期钩子中可以使用</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-在无状态组件中可以通过参数传入"><span class="nav-number">1.3.4.</span> <span class="nav-text">4. 在无状态组件中可以通过参数传入</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-React-context的局限性"><span class="nav-number">1.3.5.</span> <span class="nav-text">5. React context的局限性</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <!--<i class="fa fa-user"></i>-->
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">淡退</span>
</div>
<!--
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.3.0</div>
-->
        








        
      </div>
    </footer>
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
      </div>

    

  </div>

  
  <script src="/lib/jquery/index.js?v=3.4.1"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

<script src="/js/utils.js?v=7.3.0"></script>
  <script src="/js/motion.js?v=7.3.0"></script>


  <script src="/js/affix.js?v=7.3.0"></script>
  <script src="/js/schemes/pisces.js?v=7.3.0"></script>



<script src="/js/next-boot.js?v=7.3.0"></script>




  















  <script src="/js/local-search.js?v=7.3.0"></script>














  

  

  


  
  <script src="/js/scrollspy.js?v=7.3.0"></script>
<script src="/js/post-details.js?v=7.3.0"></script>


  <script type="text/javascript" src="//cdn.bootcss.com/canvas-nest.js/1.0.0/canvas-nest.min.js"></script>
</body>
</html>
